package com.hjy.handler;

import com.hjy.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用于绑定路径和Handler之间的关系
 */
public class HandlerMapping {
    public Map<String, Handler> mapping = new HashMap<>();

    public Handler getMapping(String path) {
        return mapping.get(path);
    }

    /**
     * 具体的绑定过程
     */
    public void process(List<Object> beanList) {
        for (Object bean : beanList) {
            // 然后获取其每个方法
            String path1 = "";
            RequestMapping annotation = bean.getClass().getAnnotation(RequestMapping.class);
            if (annotation != null) {
                path1 = annotation.value();
            }
            Method[] declaredMethods = bean.getClass().getDeclaredMethods();
            for (Method declaredMethod : declaredMethods) {
                RequestMapping requestMapping = declaredMethod.getDeclaredAnnotation(RequestMapping.class);
                if (requestMapping == null) {
                    continue;
                }
                String path2 = requestMapping.value();
                Handler handler = new Handler(bean, declaredMethod);
                mapping.put(path1 + path2, handler);
            }
        }
    }
}
